import {Alert, Button, StyleSheet, Text, TextInput} from 'react-native';
import TouchableView from '../CustomComponents/TouchableView';
import {useState, memo} from 'react';
import StorageManager from '../Storage/StorageManager';

// Initial Type
type RegisterType = {userId: string; password: string};
// Initial variable
let originalUserId = '';
let originalPassword = '';
let registerModel: RegisterType = {userId: '', password: ''};
let userIDCheckPass = false;
let passwordCheckPass = false;
let repeatPasswordCheckPass = false;
/**
 * Custom Component
 */
const InputGroup = memo(
  (props: {
    title: string;
    placeholder: string;
    errorMessage?: string;
    isTop?: boolean;
    customChangeText?: (inputText: string) => void;
  }) => {
    return (
      <>
        <Text style={[styles.textStyle, props.isTop ? {marginTop: 100} : {}]}>
          {props.title}
        </Text>
        <TextInput
          style={styles.inputStyle}
          placeholder={props.placeholder}
          onChangeText={props.customChangeText}
        />
        <Text style={styles.errorMessageStyle}>{props.errorMessage}</Text>
      </>
    );
  },
);

const Register = () => {
  const [matchError, setMatchError] = useState(false);
  const [registerDisabled, setRegisterDisabled] = useState(true);
  // User ID check
  const checkUserId = (inputText: string) => {
    originalUserId = inputText;
    if (inputText.length > 6) {
      userIDCheckPass = true;
    } else {
      userIDCheckPass = false;
    }
    checkRegisterDisable();
  };
  // Copy original password
  const copyPassword = (inputText: string) => {
    originalPassword = inputText;
    if (inputText.length == 0) {
      passwordCheckPass = false;
    } else {
      passwordCheckPass = true;
    }
    checkRegisterDisable();
  };
  // Repeat password match check
  const checkRepeatPassword = (inputText: string) => {
    if (originalPassword == inputText) {
      if (matchError) {
        setMatchError(false);
        repeatPasswordCheckPass = true;
      }
    } else {
      if (!matchError) {
        setMatchError(true);
        repeatPasswordCheckPass = false;
      }
    }
    checkRegisterDisable();
  };
  // Register button disabled check
  const checkRegisterDisable = () => {
    if (userIDCheckPass && passwordCheckPass && repeatPasswordCheckPass) {
      if (registerDisabled) {
        setRegisterDisabled(false);
      }
    } else {
      if (!registerDisabled) {
        setRegisterDisabled(true);
      }
    }
  };
  // Register button click
  const registerClick = () => {
    registerModel.userId = originalUserId;
    registerModel.password = originalPassword;
    StorageManager.storeObject<RegisterType>('User', registerModel).then(() => {
      Alert.alert('Register Success!')
    }).catch(() => {
      Alert.alert('Oops! Register Error!')
    })
  };

  return (
    <TouchableView>
      <InputGroup
        title="User ID"
        placeholder="Please enter your user ID"
        isTop={true}
        customChangeText={checkUserId}
      />
      <InputGroup
        title="Password"
        placeholder="Please enter your password"
        customChangeText={copyPassword}
      />
      <InputGroup
        title="Repeat password"
        placeholder="Please enter your password"
        errorMessage={
          matchError ? 'Oops! Passwords do not match. Please try it again.' : ''
        }
        customChangeText={checkRepeatPassword}
      />
      <Button
        title="Register"
        onPress={registerClick}
        color="steelblue"
        disabled={registerDisabled}
      />
    </TouchableView>
  );
};

const styles = StyleSheet.create({
  containerView: {
    flex: 1,
    backgroundColor: 'white',
  },
  textStyle: {
    marginLeft: 30,
    marginRight: 30,
    marginBottom: 10,
    fontSize: 15,
    fontWeight: 'bold',
    color: 'steelblue',
  },
  inputStyle: {
    marginLeft: 30,
    marginRight: 30,
    height: 40,
    borderWidth: 1,
    borderRadius: 5,
    borderColor: '#ddd',
    fontSize: 15,
    padding: 5,
  },
  errorMessageStyle: {
    marginTop: 5,
    marginBottom: 5,
    marginLeft: 30,
    marginRight: 30,
    height: 20,
    fontSize: 13,
    color: 'lightcoral',
  },
});
export default Register;
